import pymysql
from loguru import logger
from pymysql.cursors import DictCursor

from common.ConfigUtil import config
from common.LoggerUtil import log


class DBHandler:
    """mysql数据库工具类"""

    def __init__(self,
                 host,
                 port,
                 user,
                 password,
                 charset='utf8',

                 database='octopus',
                 cursorclass=DictCursor,
                 **kw
                 ):
        # 建立连接
        self.conn = pymysql.connect(
            host=host,
            port=port,
            user=user,
            password=password,
            charset=charset,
            database=database,
            # 查询出的结果由元祖变为字典
            cursorclass=DictCursor

        )

        # 建立游标

        self.cursor = self.conn.cursor()

    # 不使用format而使用args进行参数传递是为了防止sql注入
    # args是元祖，列表或者字典类型
    def query_one(self, sql, args=None):
        """查询一条记录"""
        self.cursor.execute(sql, args)
        # 事务，数据状态同步
        self.conn.commit()
        log.info(f"开始执行SQL语句-{sql}-,查询结果是：{self.cursor.fetchone()}")
        return self.cursor.fetchone()

    def query_all(self, sql, args=None):
        self.cursor.execute(sql, args)
        self.conn.commit()
        log.info(f"开始执行SQL语句-{sql}-,查询结果是：{self.cursor.fetchall()}")
        return self.cursor.fetchall()

    # 查询

    def query(self, sql, args=None, one=True):
        if one:
            return self.query_one(sql, args)
        return self.query_all(sql, args)

    # 关闭游标和连接
    def close(self):
        self.cursor.close()
        self.conn.close()


# db = DBHandler(config.read("db", "host"), int(config.read("db", "port")), config.read("db", "user"),
#             config.read("db", "password"))
#
# if __name__ == '__main__':
#     sql = "SELECT * FROM gen_table WHERE table_id = %s;"
#     print(db.query(sql, args=[1, ]))
